#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    needDeleteThread = false;
    ui->stopButton->setEnabled(false);
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::on_startButton_clicked()
{
    for (int i = 0; i < MAXSIZE; ++i)
    {
        workThread[i] = new WorkThread();
//        connect(workThread[i], SIGNAL(finished()), this, SLOT(deleteLater())); // 线程结束时销毁
    }

    needDeleteThread = true;

    for (int i = 0; i < MAXSIZE; ++i)
    {
        workThread[i]->start();
    }

    ui->startButton->setEnabled(false);
    ui->stopButton->setEnabled(true);
}

void Dialog::on_stopButton_clicked()
{
    for (int i = 0; i < MAXSIZE; ++i)
    {
        workThread[i]->terminate(); // 停止线程，何时停止有操作系统决定
        workThread[i]->wait(); // 等待线程结束
    }

    ui->startButton->setEnabled(true);
    ui->stopButton->setEnabled(false);
}

void Dialog::on_quitButton_clicked()
{
    if (needDeleteThread)
    {
        for (int i = 0; i < MAXSIZE; ++i)
        {
            workThread[i]->terminate(); // 停止线程，何时停止有操作系统决定。实际应用中可以发送一个信号通知线程退出
            workThread[i]->wait(); // 等待线程结束

            delete workThread[i];
        }
    }

    close();
}
